﻿using System;
using System.Collections.Generic;
using UnityEngine;

//所有的update都在这里注册
public enum SchedulerPriority
{
    WaitingConnect = -1001,
    NetLoop = -1000,
	HeartBeat = -950,
    GameLogic = -900,
    BattleLogic = -800,
	JoyStick = -700,
	
}

public class SchedulerManager : MonoBehaviour
{
    private static SchedulerManager _instance = null;
    public static SchedulerManager Instance
    {
	    get{return _instance;}
    }

    private SortedList<SchedulerPriority, Action> _schedulerFixedList = new SortedList<SchedulerPriority, Action>();
    private SortedList<SchedulerPriority,Action> _schedulerList = new SortedList<SchedulerPriority, Action>();
    private List<SchedulerPriority> _removeList = new List<SchedulerPriority>();
    private void Start()
    {
        _instance = this;
    }
    /// <summary>
    /// 添加调度
    /// </summary>
    /// <returns>优先级重复 返回false</returns>
    /// <param name="priority">优先级越小越早执行</param>
    /// <param name="func">回调函数</param>
    public bool AddScheduler(SchedulerPriority priority, Action func)
    {
	    if (_schedulerList.ContainsKey(priority))
	    {
		    return false;
	    }
	    _schedulerList.Add(priority, func);

	    return true;
    }

    public bool AddFixedScheduler(SchedulerPriority priority, Action func)
    {
	    if (_schedulerFixedList.ContainsKey(priority))
	    {
		    return false;
	    }
	    _schedulerFixedList.Add(priority,func);
	    return true;
    }

    public void RemoveScheduler(SchedulerPriority priority)
    {
	    //放入等待删除列表
	    if (_schedulerFixedList.ContainsKey(priority))
	    {
		    _removeList.Add(priority);
	    }

	    if (_schedulerList.ContainsKey(priority))
	    {
		    _removeList.Add(priority);
	    }
    }

    private void Update()
    {
    //		Debug.LogFormat("ScheduleManager Update {0}",Time.deltaTime.ToString());
	    foreach(var one in _schedulerList)
	    {
		    one.Value();
	    }

	    foreach (var one in _removeList)
	    {
		    _schedulerList.Remove(one);
	    }
	    _removeList.Clear();
    }

    private void FixedUpdate()
    {
    //		Debug.LogFormat("ScheduleManager FixedUpdate {0}",Time.deltaTime.ToString());

	    foreach(var one in _schedulerFixedList)
	    {
		    one.Value();
	    }

	    foreach (var one in _removeList)
	    {
		    _schedulerFixedList.Remove(one);
	    }
	    _removeList.Clear();
    }
}
	